<template>
  <div>
    <!-- 面包屑导航 -->
    <Breadcrumb />
    <!-- 添加按鈕 -->
    <el-button
      type="primary"
      style="margin-bottom: 20px"
      @click="addOrUpdateDialogVisible = true"
      >添加角色</el-button
    >
    <el-card>
      <!-- 角色表格 -->
      <el-table :data="roleList" style="width: 100%; margin-top: 30px" border>
        <el-table-column type="expand">
          <template slot-scope="{ row }">
            <el-row
              type="flex"
              align="middle"
              :class="['bdbottom', index == 0 ? 'bdtop' : '']"
              v-for="(level1, index) in row.children"
              :key="level1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(row, level1.id)">
                  {{ level1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级三级权限 -->
              <el-col :span="19">
                <el-row
                  type="flex"
                  align="middle"
                  v-for="level2 in level1.children"
                  :key="level2.id"
                  :class="['bdtop']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="danger"
                      closable
                      @close="removeRightById(row, level2.id)"
                    >
                      {{ level2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="success"
                      v-for="level3 in level2.children"
                      :key="level3.id"
                      closable
                      @close="removeRightById(row, level3.id)"
                    >
                      {{ level3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column align="center" type="index" label="序号" width="180">
        </el-table-column>
        <el-table-column
          align="center"
          prop="roleName"
          label="角色名称"
          width="180"
        >
        </el-table-column>
        <el-table-column align="center" prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column align="center" prop="address" label="操作">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="updateRole(row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="deletRole(row)"
              >删除</el-button
            >
            <el-button
              type="success"
              size="small"
              icon="el-icon-setting"
              @click="showSetRightDialog(row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加修改角色对话框 -->
    <el-dialog
      :title="isEdit ? '编辑角色' : '添加角色'"
      :visible.sync="addOrUpdateDialogVisible"
      width="50%"
      @close="resetData"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addOrUpdateForm"
        :rules="rules"
        label-width="100px"
        ref="addOrUpdateFormRef"
      >
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="addOrUpdateForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addOrUpdateForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addOrUpdateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      @closed="resetRightData"
      title="提示"
      :visible.sync="setRightDialogVisible"
      width="50%"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="defkeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="toSetRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data() {
    return {
      roleList: [],
      addOrUpdateForm: {
        roleName: "",
        roleDesc: "",
      },
      //添加修改对话框标题
      isEdit: false,
      //控制添加或修改角色对话框
      addOrUpdateDialogVisible: false,
      //控制分配权限对话框
      setRightDialogVisible: false,
      //所有权限列表
      rightsList: [],
      //树形控件属性绑定
      treeProps: {
        label: "authName",
        children: "children",
      },
      //默认选中节点id值数组
      defkeys: [],
      rules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      roleId: "",
    };
  },
  created() {
    this.getRoleList();
  },
  methods: {
    async getRoleList() {
      const res = await this.$http.reqRole();
      if (res.meta.status === 200) {
        this.roleList = res.data;
      } else {
        this.$message.error("获取角色列表失败");
      }
    },
    //删除角色权限
    removeRightById(role, rightId) {
      this.$confirm("确认删除该权限？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$http.deleteRoleRight(role.id, rightId);
          if (res.meta.status !== 200) {
            return this.$message.error("删除失败");
          }
          role.children = res.data;
          this.$message.success("删除成功");
        })
        .catch(() => {
          this.$message.warning("已取消删除");
        });
    },
    //点击编辑
    updateRole(row) {
      this.isEdit = true;
      this.addOrUpdateForm = { ...row };
      this.addOrUpdateDialogVisible = true;
    },
    //添加或编辑角色
    addRoleInfo() {
      const { id } = this.addOrUpdateForm;
      const { isEdit } = this;
      this.$nextTick(() => {
        this.$refs.addOrUpdateFormRef.validate(async (valid) => {
          if (valid) {
            if (isEdit) {
              const res = await this.$http.updateRole(id, this.addOrUpdateForm);
              if (res.meta.status !== 200) {
                return this.$message.error("修改角色信息失败");
              }
              this.addOrUpdateDialogVisible = false;
              this.getRoleList();
              this.$message.success("修改角色信息成功");
            } else {
              const res = await this.$http.addRole(this.addOrUpdateForm);
              if (res.meta.status !== 201) {
                return this.$message.error("添加角色失败");
              }
              this.$message.success("添加角色信息成功");
              this.addOrUpdateDialogVisible = false;
              this.getRoleList();
            }
          } else {
            this.$message.error(isEdit ? "修改失败" : "添加失败");
            return false;
          }
        });
      });
    },
    //重置添加对话框
    resetData() {
      this.$nextTick(() => {
        this.$refs.addOrUpdateFormRef.resetFields();
        this.addOrUpdateForm = {
          roleName: "",
          roleDesc: "",
        };
        this.isEdit = false;
      });
    },
    //重置id列表数据
    resetRightData() {
      this.defkeys = [];
    },
    //删除角色
    async deletRole(row) {
      this.$confirm("确认删除该角色？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$http.deleteRole(row.id);
          if (res.meta.status !== 200) {
            return this.$message.error("删除失败");
          }
          this.getRoleList();
          this.$message.success("删除成功");
        })
        .catch(() => {
          this.$message.warning("已取消删除");
        });
    },
    //点击分配权限，获取所有权限列表
    async showSetRightDialog(role) {
      this.roleId = role.id;
      const res = await this.$http.reqRightTree();
      if (res.meta.status !== 200) {
        return this.$message.error("获取树形列表失败");
      }
      this.rightsList = res.data;
      this.getLeafKeys(role, this.defkeys);
      this.setRightDialogVisible = true;
    },
    //递归获取角色下所有三级权限的id保存到defkeys数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    //分配给角色权限
    async toSetRight() {
      const checkedList = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = checkedList.join(",");
      const res = await this.$http.setRight(this.roleId, { rids: idStr });
      if (res.meta.status !== 200) {
        this.$message.error("分配权限失败");
      }
      this.$message.success("分配权限成功");
      this.getRoleList();
      this.setRightDialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdbottom {
  border-top: 1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
</style>
